package com.bst.bsj.weixin;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 微信 js sdk
 * 
 * @author apple
 *
 */
public abstract class WeixinJSSDK {

	private static final Log logger = LogFactory.getLog(WeixinJSSDK.class);

	/**
	 * 获取 js api
	 * 
	 * @param access_token
	 * @return
	 */
	public static String getJsApiTicket(String access_token) {

		String f = System.getProperty("jsse.enableSNIExtension");
		if (!"false".equals(f)) {
			System.setProperty("jsse.enableSNIExtension", "false");
		}

		// TODO Auto-generated method stub
		String targetURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ access_token + "&type=jsapi";
		GetMethod method = new GetMethod(targetURL);
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(5000);

		try {
			int status = client.executeMethod(method);

			if (status == HttpStatus.SC_OK) {
				String responseContent = HttpClientUtil.getResponseBody(
						method.getResponseBodyAsStream(),
						HttpClientUtil.getResponseHeaderCharset(method));
				JSONObject ja = (JSONObject) JSON.parse(responseContent);

				// 获取 ticket
				String ticket = ja.getString("ticket");
				if (ticket == null) {
					throw new Exception(responseContent);
				}

				return ticket;
			}

		} catch (Exception e) {

			logger.error("获取ticket异常", e);

		} finally {
			method.releaseConnection();
		}

		return null;
	}

	/**
	 * 三元组，0:noncestr，1:timestamp，2:signature
	 * 
	 * @param url
	 * @param ticket
	 * @return
	 */
	public static Map<String, String> getWxJsConfig(String url, String ticket) {

		String noncestr = WeixinPayV3Util.getNonceStr();
		String timestamp = WeixinPayV3Util.getUnixTimestamp();

		Map<String, String> params = new HashMap<String, String>();
		params.put("noncestr", noncestr);
		params.put("jsapi_ticket", ticket);
		params.put("timestamp", timestamp);
		params.put("url", url);

		String signature = WeixinPayV3Util.SHASign(params);
		params.put("signature", signature);
		return params;
	}
}
